package org.linlinjava.litemall.admin.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.dto.WebProAndArtAllinone;
import org.linlinjava.litemall.admin.vo.CatVo;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallWebCategory;
import org.linlinjava.litemall.db.domain.LitemallWebProduct;
import org.linlinjava.litemall.db.service.LitemallWebCategoryService;
import org.linlinjava.litemall.db.service.LitemallWebProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/webproduct")
@Validated
public class AdminWebProductController {
    private final Log logger = LogFactory.getLog(AdminWebProductController.class);

    @Autowired
    private LitemallWebProductService productService;
    @Autowired
    private LitemallWebCategoryService categoryService;
    @RequiresPermissions("admin:webproduct:list")
    @RequiresPermissionsDesc(menu = {"网站管理", "产品管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(Integer id, String name,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        return ResponseUtil.okList(productService.list(id, name, page, limit, sort, order));
    }
    private Object validate(LitemallWebProduct product) {
        String name = product.getName();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.badArgument();
        }

        Integer cid = product.getCid();
        if (cid<0 || cid == null) {
            return ResponseUtil.badArgument();
        }

        return null;
    }
    public Object list2(List<LitemallWebCategory> l1CatList) {
        List<CatVo> categoryList = new ArrayList<>(l1CatList.size());
        for (LitemallWebCategory l1 : l1CatList) {
            CatVo l1CatVo = new CatVo();
            l1CatVo.setValue(l1.getId());
            l1CatVo.setLabel(l1.getName());

            List<LitemallWebCategory> l2CatList = categoryService.queryByPid(l1.getId());
            if(org.apache.commons.collections.CollectionUtils.isNotEmpty(l2CatList)) {
                List<CatVo> children = new ArrayList<>(l2CatList.size());
                for (LitemallWebCategory l2 : l2CatList) {
                    CatVo l2CatVo = new CatVo();
                    l2CatVo.setValue(l2.getId());
                    l2CatVo.setLabel(l2.getName());
                    children.add(l2CatVo);
                }
                l1CatVo.setChildren(children);
            }
            categoryList.add(l1CatVo);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("categoryList",categoryList);
        return ResponseUtil.ok(data);
    }
    @GetMapping("/productcategory")
    public Object productCategory() {
        List<LitemallWebCategory> l1CatList = categoryService.queryL1ForType("0");
        return list2(l1CatList);
    }
    @GetMapping("/articlecategory")
    public Object articleCategory() {
        List<LitemallWebCategory> l1CatList = categoryService.queryL1ForType("1");
        return list2(l1CatList);
    }

    @RequiresPermissions("admin:webproduct:create")
    @RequiresPermissionsDesc(menu = {"网站管理", "产品管理"}, button = "添加")
    @PostMapping("/create")
    public Object create(@RequestBody WebProAndArtAllinone product) {
        Object error = validate(product.getProducts());
        if (error != null) {
            return error;
        }
        productService.add(product.getProducts());
        return ResponseUtil.ok();
    }

    @RequiresPermissions("admin:webproduct:read")
    @RequiresPermissionsDesc(menu = {"网站管理", "产品管理"}, button = "详情")
    @GetMapping("/detail")
    public Object read(@NotNull Integer id) {
        LitemallWebProduct product = productService.findById(id);
        Map<String, Object> data = new HashMap<>();
        data.put("product", product);
        return ResponseUtil.ok(data);
    }

    @RequiresPermissions("admin:webproduct:update")
    @RequiresPermissionsDesc(menu = {"网站管理", "产品管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody WebProAndArtAllinone product) {
        Object error = validate(product.getProducts());
        if (error != null) {
            return error;
        }

        if (productService.updateById(product.getProducts()) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        return ResponseUtil.ok();
    }

    @RequiresPermissions("admin:webproduct:delete")
    @RequiresPermissionsDesc(menu = {"网站管理", "产品管理"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody LitemallWebProduct product) {
        Integer id = product.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }
        productService.deleteById(id);
        return ResponseUtil.ok();
    }
}
